package gitobject;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import Utils.tempWorkTree;
import fileoperation.FileReader;
import sha1.SHA1;
import repository.Repository;
import zlib.ZLibUtils;

public class Commit extends GitObject{
    protected String tree; 		// the sha1 value of present committed tree
    protected String parent; 	// the sha1 value of the parent commit
    protected String author; 	// the author's name and timestamp
    protected String committer; // the committer's info
    protected String message; 	// the commit memo
    protected String time;

    private String value;


    public String getParent(){return parent;}
    public String getTree(){return tree;}
    public String getAuthor(){return author;}
    public String getCommitter(){return committer;}
    public String getMessage(){return message;}
    public String getValue(){return value;}
    public String getTime(){return time;}
    public Commit(){}
    /**
     * Construct a commit from a built tree.
     * @param
     * author, committer, message鍙傛暟鍦╣it commit鍛戒护閲屽垱寤�
     * @throws Exception
     */
    
    public Commit(Tree t, String author, String committer, String message) throws Exception {
        this.fmt = "commit"; 	//type of object
        this.tree = t.getKey(); 
        this.parent =getLastCommit(); //getLastCommit() == null ? "" : getLastCommit(); //null means there is no parent commit.
        this.author = author;
        this.committer = committer;
        this.message = message;
        this.time=LocalDateTime.now().toString();
        this.value = this.parent+" " + this.key +" "+ this.tree;
        key = genKey();
        this.value = this.parent+" " + this.key +" "+ this.tree;
        compressWrite();
    }
    
    /**
     * Deserialize the commit object from its key(commitId)
     * @param Id
     * @throws IOException
     */
    
    //反序列化
    public static Commit deserialize(String Id) throws IOException {
        try {
            
            File dir = new File(tempWorkTree.gitDir+File.separator+"objects");
            File[] fs = dir.listFiles();
            for (int i = 0; i < fs.length; i++) {
                if (fs[i].isFile() && fs[i].getName().equals(Id)) {
                    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(fs[i]));
                    Commit commit = (Commit) objectInputStream.readObject();
                    return commit;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    /**
     * Generate the hash value of this commit.
     * @return key
     * */
    public String genKey() throws Exception {
        key = SHA1.getHash(value);
        return key;
    }


    /**
     * Get the parent commit from the HEAD file.
     * @return
     * @throws IOException
     */
    public static String getLastCommit() throws IOException {
        
        File HEAD = new File(tempWorkTree.gitDir + File.separator + "HEAD");

        String path = getValue(HEAD).substring(5).replace("\n", "");
        File branchFile = new File(tempWorkTree.gitDir + File.separator + path);

        if (branchFile.isFile()) {
            String temp=getValue(branchFile).replace("\n","");
            return temp;
        } else {
            return null;
        }
    }

    public static String getValue(File file) throws IOException {
        String filepath = file.getPath();
        StringBuffer sb = new StringBuffer();
        readToBuffer(sb, filepath);
        return sb.toString();
    }
    //读取路径
    public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
        InputStream is = new FileInputStream(filePath);
        String line; 
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        line = reader.readLine(); 
        while (line != null) {
            buffer.append(line); 
            buffer.append("\n"); 
            line = reader.readLine(); 
        }
        reader.close();
        is.close();
    }

    @Override
    public String toString() {
        return "commit  "+key+"  ("+"褰撳墠鍒嗘敮"+")\n"
                +"Author:\t"+author+"\n"
                +"Date:\t"+time+"\n"
                +message+"\n";
    }
}

